package com.itheima.reggie.controller;

import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.entity.R;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired(required = false)
    private AddressBookService addressBookService;

    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook, HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        addressBook.setUserId(userId);
        addressBook.setCreateUser(userId);
        addressBook.setUpdateUser(userId);
        addressBookService.save(addressBook);

        return R.success("保存成功");
    }

    @GetMapping("list")
    public R<List<AddressBook>> findAll(HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        R<List<AddressBook>> result = addressBookService.findAll(userId);
        return result;
    }

    @PutMapping("/default")
    public R<AddressBook> updateDefault(@RequestBody AddressBook addressBook,HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        addressBook.setUserId(userId);

        addressBookService.updateDefault(addressBook);

        return R.success(addressBook);
    }

    @GetMapping("/{id}")
    public R<AddressBook> findById(@PathVariable Long id){
        R<AddressBook> result = addressBookService.findById(id);
        return result;
    }

    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook,HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        // addressBook.setUserId(userId);
        addressBook.setUpdateUser(userId);

        addressBookService.update(addressBook);
        return R.success("修改成功");
    }

    @DeleteMapping
    public R<String> delete(Long ids){

        addressBookService.delete(ids);
        return R.success("删除成功");
    }

    @GetMapping("/default")
    public R<AddressBook> getDefault(HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        AddressBook addressBook = addressBookService.getDefaultAddress(userId);

        if (addressBook == null) {
            return R.error("没有找到该对象");
        } else {
            return R.success(addressBook);
        }
    }
}
